package com.pubinfo.passbook.common.handler.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.pubinfo.passbook.common.enums.ContractStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.List;

/**
 * @Author litiewang
 * @Date 2022/6/15 14:52
 * @Version 1.0
 */
@Slf4j
public class CustomSheetWriteHandler implements SheetWriteHandler {
  private int count = 0;
  
  public CustomSheetWriteHandler(int count) {
    this.count = count;
  }
  
  @Override
  public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
  
  }
  
  @Override
  public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    log.info("第{}个Sheet写入成功。", writeSheetHolder.getSheetNo());
    
    Sheet sheet = writeSheetHolder.getSheet();
    // 设置单元格下拉框
    CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, count, 10, 10);
    DataValidationHelper helper = sheet.getDataValidationHelper();
    // 数据可从数据库查询
    
    List<String> list = ContractStatusEnum.getValues();
    DataValidationConstraint constraint = helper.createExplicitListConstraint(list.toArray(new String[list.size()]));
    
    DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
    sheet.addValidationData(dataValidation);
  }
}